import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    vueJsx(),
    vueDevTools(),
    AutoImport({
      resolvers: [ElementPlusResolver()],
      // 自动导入优化
      imports: ['vue', 'vue-router', 'pinia'],
      dts: true,
      eslintrc: {
        enabled: true,
      },
    }),
    Components({
      resolvers: [ElementPlusResolver()],
      // 组件自动导入优化
      dts: true,
      include: [/\.vue$/, /\.vue\?vue/],
    }),
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    },
  },
  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@use "@/styles/element/index.scss" as *;`
      }
    }
  },
  // 构建优化配置
  build: {
    target: 'es2015',
    minify: 'terser',
    rollupOptions: {
      output: {
        // 代码分割策略
        manualChunks: {
          // 第三方库分离
          'vendor': ['vue', 'vue-router', 'pinia'],
          'element-plus': ['element-plus'],
          'utils': ['lodash-es'],
          // 组件库分离
          'widgets': [
            './src/components/widgets/TextWidget.vue',
            './src/components/widgets/ButtonWidget.vue',
            './src/components/widgets/ImageWidget.vue',
            './src/components/widgets/ContainerWidget.vue'
          ],
          // 设计器核心
          'designer': [
            './src/components/designer/ComponentRenderer.vue'
          ]
        },
        // 文件名策略
        chunkFileNames: 'assets/js/[name]-[hash].js',
        entryFileNames: 'assets/js/[name]-[hash].js',
        assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
      }
    },
    // 启用源码映射（生产环境可关闭）
    sourcemap: false,
    // 分块大小警告阈值
    chunkSizeWarningLimit: 1000
  },
  // 开发服务器优化
  server: {
    hmr: {
      overlay: false
    }
  },
  // 依赖预构建优化
  optimizeDeps: {
    include: [
      'vue',
      'vue-router', 
      'pinia',
      'element-plus',
      'lodash-es'
    ],
    exclude: [
      // 排除不需要预构建的依赖
    ]
  },
  // 性能监控
  define: {
    __VUE_PROD_DEVTOOLS__: false
  }
})
